<template>
	<view class="video-player-container">
		<video id="courseVideo" :src="currentplayUrl" class="course-video" :title="videoTitle" :poster="videoCover"
			:controls="true" :show-center-play-btn="true" :show-fullscreen-btn="true" :initial-time="currentTime"
			:object-fit="objectFit" @error="handleVideoError" @ended="handleEnded" @timeupdate="handleTimeUpdate"
			@play="handleVideoPlay" @pause="handleVideoPause" :autoplay="false"></video>

		<!-- 清晰度选择器 -->
		<cover-view class="definition-selector" v-if="playInfoList.length > 1 && showDefinitionSelector">
			<cover-view class="definition-list">
				<cover-view v-for="item in playInfoList" :key="item.value" class="definition-item"
					:class="{ active: currentDefinition === item.value }" @tap="switchDefinition(item)">
					<cover-view class="label">{{ item.label }}</cover-view>
				</cover-view>
			</cover-view>
		</cover-view>

		<!-- 清晰度切换按钮 -->
		<cover-view class="definition-btn" @tap="toggleDefinitionSelector">
			<cover-view class="current-definition">{{ getCurrentDefinitionLabel }}</cover-view>
		</cover-view>

		<!-- 广告容器 -->
		<cover-view class="ad-container" v-if="adList.length > 0 && showAd && isPaused">
			<cover-image :src="currentAd.imageUrl" class="ad-image" @tap="handleAdClick(currentAd)"></cover-image>
			<cover-view class="close-btn" @tap.stop="closeAd">
				<cover-view class="close-icon">×</cover-view>
			</cover-view>
		</cover-view>
	</view>
</template>

<script>
	export default {
		name: "VideoPayCoursePlayer",

		props: {
			playInfoList: {
				type: Array,
				default: () => [],
				required: true
			},
			videoTitle: {
				type: String,
				default: ''
			},
			videoCover: {
				type: String,
				default: ''
			},
			adList: {
				type: Array,
				default: () => []
			},
			historyProgress: {
				type: Number,
				default: 0
			}
		},

		data() {
			return {
				currentAdIndex: 0,
				showAd: false,
				isPaused: false,
				autoPlayTimer: null,
				currentplayUrl: '',
				currentDefinition: '',
				currentTime: 0,
				videoContext: null,
				objectFit: 'contain',
				showDefinitionSelector: false,
				isPauseConfirmed: false,
				pauseCheckTimer: null,
			}
		},

		computed: {
			currentAd() {
				return this.adList[this.currentAdIndex] || {}
			},
			getCurrentDefinitionLabel() {
				const current = this.playInfoList.find(item => item.value === this.currentDefinition);
				return current ? current.label : '自动';
			}
		},

		watch: {
			historyProgress: {
				handler(newVal) {
					if (newVal > 0 && this.videoContext) {
						this.currentTime = newVal;
						this.videoContext.seek(newVal);
					}
				},
				immediate: true
			},
			playInfoList: {
				handler(newVal) {
					if (newVal && newVal.length > 0) {
						this.initDefaultDefinition()
					}
				},
				immediate: true
			}
		},

		created() {
			this.initDefaultDefinition()
			this.isPaused = true;
			if (this.historyProgress > 0) {
				this.currentTime = this.historyProgress;
			}
		},

		mounted() {
			this.videoContext = uni.createVideoContext('courseVideo', this)
			if (this.historyProgress > 0) {
				this.$nextTick(() => {
					this.videoContext.seek(this.historyProgress);
				});
			}
		},

		methods: {
			handleVideoPause() {
				if (this.pauseCheckTimer) {
					clearTimeout(this.pauseCheckTimer);
				}

				this.isPaused = true;

				this.pauseCheckTimer = setTimeout(() => {
					if (this.isPaused) {
						this.isPauseConfirmed = true;
						this.$emit('pause');

						if (this.adList.length > 0) {
							this.showAd = true;
							this.startAdAutoPlay();
						}
					}
				}, 200);
			},

			handleVideoPlay() {
				if (this.pauseCheckTimer) {
					clearTimeout(this.pauseCheckTimer);
				}

				this.isPaused = false;
				this.isPauseConfirmed = false;
				this.showAd = false;
				this.$emit('play');
				this.clearAdAutoPlay();
			},

			closeAd() {
				this.showAd = false
				this.clearAdAutoPlay()
			},

			startAdAutoPlay() {
				this.clearAdAutoPlay()
				this.autoPlayTimer = setInterval(() => {
					this.currentAdIndex = (this.currentAdIndex + 1) % this.adList.length
				}, 3000)
			},

			clearAdAutoPlay() {
				if (this.autoPlayTimer) {
					clearInterval(this.autoPlayTimer)
					this.autoPlayTimer = null
				}
			},

			initDefaultDefinition() {
				if (this.playInfoList.length > 0) {
					const sortedList = [...this.playInfoList].sort((a, b) => {
						const defOrder = {
							'FD': 1,
							'LD': 2,
							'SD': 3,
							'HD': 4,
							'2K': 5,
							'4K': 6
						}
						return defOrder[b.definition] - defOrder[a.definition]
					})

					const defaultPlayInfo = sortedList[0]
					if (defaultPlayInfo && defaultPlayInfo.playUrl) {
						this.switchDefinition(defaultPlayInfo)
					}
				}
			},
			// 发起播放完成事件
			handleEnded() {
				this.$emit('ended');
			},

			switchDefinition(item) {
				if (!item || !item.playUrl) return;

				const currentTime = this.currentTime;
				const wasPlaying = !this.isPaused;

				this.showAd = false;
				this.clearAdAutoPlay();

				this.currentDefinition = item.value;
				this.currentplayUrl = item.playUrl;
				this.showDefinitionSelector = false;

				this.$nextTick(() => {
					if (this.videoContext) {
						this.videoContext.seek(currentTime);
						if (wasPlaying) {
							setTimeout(() => {
								this.videoContext.play();
							}, 100);
						}
					}
				});
			},

			handleTimeUpdate(e) {
				this.currentTime = e.detail.currentTime
				this.$emit('timeupdate', e.detail)
			},

			handleVideoError(e) {
				this.$emit('error', e)
			},

			toggleDefinitionSelector() {
				this.showDefinitionSelector = !this.showDefinitionSelector;
			},

			beforeDestroy() {
				this.clearAdAutoPlay()
				if (this.pauseCheckTimer) {
					clearTimeout(this.pauseCheckTimer)
				}
				if (this.videoContext) {
					this.videoContext.stop()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import './VideoPayCoursePlayer.scss';
</style>